package com.justech.mes.utils.excel;

import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import java.lang.reflect.Field;
import java.util.ArrayList;
import java.util.List;

/**
 * @author feifei.li
 */
public class ExportForBean {

    public static String[] headers(List<ExcelUtil.Entry> columns) {
        String[] headers = new String[columns.size()];
        for (int i = 0; i < columns.size(); i++) {
            headers[i] = columns.get(i).getValue().toString();
        }
        return headers;
    }

    public static void export(String fileName, List datas, Class<?> beanClass) {
        List<ExcelUtil.Entry> columns = getHeadersForBean(beanClass);
        /*需要被导出的数据集合*/
        List<Object[]> objects = convert(datas, columns);
        ServletRequestAttributes servletRequestAttributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        ExcelUtil.excelExport(fileName, headers(columns), objects, servletRequestAttributes.getResponse());
    }

    public static List<Object[]> convert(List datas, List<ExcelUtil.Entry> columns) {
        /*需要被导出的数据集合*/
        List<Object[]> objects = new ArrayList<>(datas.size());
        /*通过反射获取属性的值*/
        for (Object o : datas) {
            Object[] rows = new Object[columns.size()];
            Class var1 = o.getClass();
            for (int i = 0; i < columns.size(); i++) {
                try {
                    Field var2 = null;
                    try {
                        var2 = var1.getDeclaredField(columns.get(i).getKey().toString());
                    } catch (NoSuchFieldException e) {
                        e.printStackTrace();
                    }
                    var2.setAccessible(true);
                    Object fieldValue = var2.get(o);
                    rows[i] = fieldValue;
                } catch (IllegalAccessException e) {
                    e.printStackTrace();
                }
            }
            objects.add(rows);
        }
        return objects;
    }

    /**
     * 获取实体的列信息
     *
     * @param c
     * @return
     */
    public static List<ExcelUtil.Entry> getHeadersForBean(Class c) {
        if (c == null) {
            throw new RuntimeException("beanClass不可以为空");
        }
        Field[] declaredFields = c.getDeclaredFields();
        /*需要导出的属性集合*/
        List<ExcelUtil.Entry> columns = new ArrayList<>(1);
        for (Field field : declaredFields) {
            Title annotation = field.getAnnotation(Title.class);
            if (annotation != null) {
                columns.add(new ExcelUtil.Entry(field.getName(), annotation.name()));
            }
        }
        return columns;
    }
}
